var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var Goods = require('../models/goods')

mongoose.connect('mongodb://127.0.0.1:27017/imoocmall')

mongoose.connection.on('connected', function () {
  console.log('MongoDB connected success')
})

mongoose.connection.on('error', function () {
  console.log('MongoDB connected fail')
})

mongoose.connection.on('disconnected', function () {
  console.log('MongoDB connected disconnected')
})

router.post('/list', function (req, res, next) {
  let page = 1
  let pageSize = 100
  let priceLevel = 'all'
  let sort = 1
  let skip = (page - 1) * pageSize
  // eslint-disable-next-line one-var
  var priceGt = '', priceLte = ''
  let params = {}
  if (priceLevel !== 'all') {
    switch (priceLevel) {
      case '0': priceGt = 0; priceLte = 100; break
      case '1': priceGt = 100; priceLte = 500; break
      case '2': priceGt = 500; priceLte = 1000; break
      case '3': priceGt = 1000; priceLte = 5000; break
    }
    params = {
      salePrice: {
        $gt: priceGt,
        $lte: priceLte
      }
    }
  }
  let goodsModel = Goods.find(params).skip(skip).limit(pageSize)
  goodsModel.sort({'salePrice': sort})
  goodsModel.exec(function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      res.json({
        code: 0,
        msg: '请求成功',
        data: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
})

router.post('/add', function (req, res, next) {
  console.log(req)
  Goods.insertMany(req.body, function (err, userDoc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      console.log('userDoc' + userDoc)
      res.json({
        code: 0,
        msg: '请求成功',
        data: '插入成功'
      })
    }
  })
})

router.post('/del', function (req, res, next) {
  var productId = req.body.productId
  console.log('del', productId)
  Goods.deleteOne({ productId: productId }, function (err, userDoc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      console.log('userDoc' + userDoc)
      res.json({
        code: 0,
        msg: '删除成功',
        data: '删除成功'
      })
    }
  })
})

module.exports = router
